<?php
class MySqlCheckService
{
	private $adminDao;
	
	public function __construct(){
		$this->adminDao = new AdminDao();
	}
	
	public function checkTables()
	{
		$resutl = array();
		$tables	= $this->getTables(C('LtConfig')->get('db.table.prefix'));
		if($tables)
		{
			foreach($tables as $table)
			{
				//检查表状态
				if(!$this->checkTable($table))
				{
					$result[] = $table;
				}
			}
		}
		return $result;
	}
	
	public function repairTables()
	{
		$result = array();
		$tables = $this->checkTables();
		foreach($tables as $table)
		{
			if($this->repairTable($table))
			{
				$result[$table] = true;
			}
			else
			{
				$result[$table] = false;
			}
		}
		return $result;
	}
	
	public function restore($restoreFile)
	{
		set_time_limit(0);
		$restoreFile	= C('LtConfig')->get('db.backup.path').$restoreFile;
		if(!is_file($restoreFile))
		{
			$this->showJsMessage ($restoreFile.'不存在，请先上传restore.sql');
		}
		else
		{
			$sql	= file_get_contents($restoreFile);
			$this->runSql($sql);
			unlink($restoreFile);
			$this->showJsMessage ('还原完毕');
		}
	}
	
	private function getTables($prefix)
	{
		$tmp 	= $this->adminDao->getDbh()->query("SHOW TABLES LIKE '".str_replace('_','\_',$prefix)."%'");
		$tables	= array();
		if($tmp)
		{
			foreach($tmp as $tv)
			{
				foreach($tv as $tvv)
				{
					$tables[]	= $tvv;
				}
			}
		}
		return $tables;
	}
	
	private function checkTable($table)
	{
		if(empty($table))
		{
			return true;
		}
		
		$tmp = $this->adminDao->getDbh()->query("CHECK TABLE ".$table);
		if(!$tmp)
		{
			return false;
		}
		
		foreach($tmp as $tv)
		{
			if($tv['Msg_type']=='status' && $tv['Msg_text']=='OK')
			{
				return true;
			}
		}
		
		return false;
	}
	
	private function repairTable($table)
	{
		$tmp = $this->adminDao->getDbh()->query("REPAIR TABLE ".$table);
		if(!$tmp)
		{
			return false;
		}
		
		foreach($tmp as $tv)
		{
			if($tv['Msg_type']=='status' && $tv['Msg_text']=='OK')
			{
				return true;
			}
		}
		
		return false;
	}
}
?>